#pragma once

#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include "Connection.hpp"
#include"Comm.hpp"
#include"HandlerConnection.hpp"

//将获取的连接添加到epoll中
class Accepter // 连接管理器
{
public:
    Accepter() {}
    // ET模式，你怎么知道，只有一条连接到来了呢？
    void AccepterConnection(Connection *conn) // conn :listensocket对应的conn
    {
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(conn->SockFd(), (struct sockaddr *)&peer, &len);
            if (sockfd > 0)
            {
                lg.LogMessage(Info, "get a new link is: %d\n", sockfd);
                //普通套接字
                SetNonblock(sockfd);
                auto recver=bind(&HandlerConnection::recver,std::placeholders::_1);
                auto sender=bind(&HandlerConnection::sender,std::placeholders::_1);
                auto excepter=bind(&HandlerConnection::execepter,std::placeholders::_1);
                Connection* normal_conn=ConnectionFatory::BuildNormalConnection(sockfd,recver,sender,excepter,EPOLLIN|EPOLLET,conn->_R);
                normal_conn->_R->AddConnection(normal_conn);
            }
            else
            {
                if (errno == EAGAIN)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    lg.LogMessage(Warning, "get a new link error\n");
                    break;
                }
            }
        }
    }
    ~Accepter() {}

private:
};
